# -*- coding: utf-8 -*-
from django.db import models,connection
from django.contrib import admin
from django.utils.text import get_valid_filename
from settings import *
from utils import guid,logs,mailer,function
from utils.components import ExecuteState

class Group(models.Model):
    """
    summary:
        群组表
    """
    name = models.CharField('名称',max_length=20)
    slug = models.CharField('slug',max_length=200)
    icon = models.ImageField('头像',upload_to='group/%Y/%m/%d',default='',blank=True)
    user_count = models.IntegerField('用户数量',default=0)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = u'群组'
        verbose_name_plural = u'群组'

class Language(models.Model):
    """
    summary:
        语言表
    """
    name = models.CharField('名称',max_length=100)
    slug = models.CharField('slug',max_length=100)
    icon = models.CharField('图标',max_length=200,default='',blank=True)
    article_count = models.IntegerField('文章数量',default=0,)

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = u'语言'
        verbose_name_plural = u'语言'

    def save(self):
        self.slug = get_valid_filename(self.slug.lower())
        super(Language,self).save()

class User(models.Model):
    """
    summary:
        用户基本信息表
    """

    STATUS_CHOICES = (
                     (0,u'未激活'),
                     (1,u'激活'),
                     (2,u'验证通过'),
                     (3,u'禁用'),
                     )

    email = models.EmailField('Email')
    password = models.CharField('密码',max_length=64,blank=True)
    realname = models.CharField('姓名',max_length=20)
    active_key = models.CharField('激活代码',max_length=64)
    score = models.IntegerField('积分',default=0)
    groups = models.ManyToManyField(Group,null=True,blank=True)
    addtime = models.DateTimeField('注册时间',auto_now=True)
    lasttime = models.DateTimeField('最后登录时间',auto_now=True)
    status = models.IntegerField('状态',choices=STATUS_CHOICES,default=0)
    signup_memo = models.TextField('申请原因')

    def __unicode__(self):
        return self.realname

    def addtime_format(self):
        return self.addtime.strftime('%Y-%m-%d %H:%M:%S')

    class Meta:
        verbose_name = u'用户'
        verbose_name_plural = u'用户'

    def check_email_exist(self):
        """
        summary:
            检查姓名是否存在
        params:
            realname        要验证的姓名
        returns:
            ExecuteState    success = True 表示不存在
        author:
            李华顺 <huacnlee@gmail.com>
        """
        state = ExecuteState()

        try:
            user = User.objects.get(email = self.email)
            state.message = "“Email”已经被他人注冊。"
            state.success = False
        except (User.DoesNotExist):
            state.success = True
            user = None

        return state


    def check(self):
        """
        summary:
            验证输入的内容是否符合要求，并返回 ExecuteState 状态
        returns:
            ExecuteState
        """
        state = ExecuteState()
        state.success = False

        if len(self.realname) < 2:
            state.message = "“姓名” 最少要求4个字符，两个中文。"
            return state

        if self.email == "":
            state.message = "“Email”还示输入或格式不符合要求。"
            return state

        state = self.check_email_exist()
        if not state.success:
            return state

        state.success = True
        return state

    def save(self,modify_pwd=False):
        """
        summary:
            save方法覆盖
        params:
            modify_pwd        是否要修改密码
        author:
            李华顺 <huacnlee@gmail.com>
        """
        # 如果改状态为通过验证时，发送mail提示
        if self.status == 2:
            mail_send = mailer.SignupActive(self)
            mail_send.start()

        # 加密码
        if modify_pwd:
            self.password = function.md5_encode(self.password)

        super(User,self).save()

    def save_simple(self):
        """
        summary:
            申请账号时所用的保存方法，会生成active_key
        """
        self.active_key = guid.generate()
        super(User,self).save()

